<template>
  <view>
    <tabTopBar
      :title="$t('network.site')"
      :isOpenRightSolt="true"
      :isOpenLeftSolt="true"
      :bgColor="'#132034'"
    >
      <template #right-content>
        <image src="/static/ops-plus.png" class="ops-add" @click="addSite" />
      </template>
    </tabTopBar>

    <view
      class="search"
      :style="{
        top: this.navbarHeight + this.statusBarHeight + 'px',
      }"
    >
      <up-search
        :placeholder="$t('network.inputSiteName')"
        v-model="searchVal"
        :showAction="false"
      ></up-search>
    </view>

    <template v-if="loadMoreStatus == 'loading' || dataList.length !== 0">
      <view
        :style="{
          paddingTop: this.navbarHeight + this.statusBarHeight - 14 + 'px',
        }"
      >
        <detailsOfThePowerPlant
          :isDisabled="false"
          :dataList="dataList"
          @handleUnbinding="handleUnbinding"
          @lookSiteDetail="lookSiteDetail"
        />
      </view>

      <up-loadmore
        :status="loadMoreStatus"
        :nomore-text="$t('network.noDataOfMore')"
        :loading-text="$t('common.loadingText')"
        color="#9e9e9e"
        lineColor="#9e9e9e"
        dashed
        :line="loadMoreStatus == 'nomore'"
      />
    </template>
    <template v-else>
      <empty />
    </template>
    <!-- <no-empty /> -->
    <up-popup
      :show="isShowModal"
      round="10"
      mode="center"
      overlay
      closeOnClickOverlay
      zIndex="998"
    >
      <view class="modal-content">
        <view class="title"> {{ $t("network.prompt") }} </view>
        <view class="header">
          {{ $t("network.inputSiteNameToo") }}
        </view>
        <view class="modal-content-input">
          <up-form
            labelPosition="left"
            :model="siteUnbinding"
            :rules="rules"
            ref="uFormRef"
          >
            <up-form-item prop="name" borderBottom>
              <up-input
                v-model="siteUnbinding.name"
                class="siteUnbinding-input"
                :placeholder="
                  unBindData.siteName
                    ? unBindData.siteName
                    : $t('network.unBindSiteName')
                "
                border="none"
                color="#fff"
                :clearable="true"
              ></up-input>
            </up-form-item>
          </up-form>
        </view>
        <view class="footer">
          <u-button
            class="btn addborder"
            :text="$t('network.cancel')"
            @click="handleClose"
          ></u-button>
          <u-button
            class="btn"
            :text="$t('network.areYouSure')"
            :loading="btnLoading"
            @click="confirm"
          ></u-button>
        </view>
      </view>
    </up-popup>

    <up-popup
      :show="isShowPoup"
      @close="close"
      closeable
      closeOnClickOverlay
      round="20"
    >
      <view class="popup">
        <view class="locale-list">
          <view
            class="locale-item"
            v-for="(item, index) in bindingData"
            :key="index"
          >
            <view
              class="locale-item"
              :class="bindingType == item.type ? 'locale-item-active' : ''"
              @click="onSelectBinDing(item)"
            >
              {{ item.text }}
            </view>
          </view>
        </view>
      </view>
    </up-popup>

    <tabBar :activated="isShow"></tabBar>
  </view>
</template>

<script>
import { useAppStore } from "@/store/app";
import apis from "@/apis/index.js";
import { cookie } from "@/utils/cookie.js";
import permision from "@/utils/permission";

export default {
  data() {
    return {
      statusBarHeight: 0,
      navbarHeight: 0,
      isShow: false,
      isShowModal: false,
      dataList: [],
      pageNum: 1,
      loadMoreStatus: "loading",
      siteUnbinding: {
        name: "",
      },
      rules: {
        name: {
          required: true,
          message: this.$t("network.unBindSiteName"),
          trigger: ["blur"],
          trigger: ["blur", "change"],
        },
      },
      btnLoading: false,
      searchVal: "",
      bindingData: [
        {
          text: this.$t("network.scanTheCodeToBind"),
          type: 1,
        },
        {
          text: this.$t("network.manualBinding"),
          type: 2,
        },
      ],
      bindingType: 1,
      isShowPoup: false,
      unBindData: {},
    };
  },
  onShow() {
    this.pageNum = 1;
    this.dataList = [];
    this.init();
    this.fetchData();
    this.isShow = true;
  },
  mounted() {},
  watch: {
    searchVal(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.searchDataList();
      }
    },
  },
  methods: {
    searchDataList() {
      this.pageNum = 1;
      this.dataList = [];
      this.fetchData();
    },
    lookSiteDetail(params) {
      uni.navigateTo({
        url: `/pages/siteDetail/siteDetail?siteId=${params.sid}&siteName=${params.siteName}`,
      });
    },
    init() {
      const store = useAppStore();
      const { getNavBarHeight, geStatusBarHeight } = store;
      this.navbarHeight = getNavBarHeight();
      this.statusBarHeight = geStatusBarHeight();
    },
    handleClose() {
      if (this.isShowModal) {
        this.isShowModal = false;
      }
    },
    confirm() {
      if (!this.btnLoading) {
        this.$refs.uFormRef
          .validate()
          .then((valid) => {
            if (valid) {
              this.btnLoading = true;

              if (this.siteUnbinding.name == this.unBindData.siteName) {
                apis
                  .unBindTheSite({
                    siteId: this.unBindData.sid,
                  })
                  .then((res) => {
                    console.log(res);
                    if (res.code == 200) {
                      this.dataList.forEach((item, index) => {
                        if (item.sid == this.unBindData.sid) {
                          this.dataList.splice(index, 1);
                          this.siteUnbinding.name = "";
                          uni.showToast({
                            title: this.$t("newwork.bindSuccess"),
                            icon: "none",
                          });
                        }
                      });
                    }
                    this.btnLoading = false;
                    this.isShowModal = false;
                  });
              } else {
                uni.showToast({
                  title: this.$t("network.siteNameNoUnanimous"),
                  duration: 2000,
                  icon: "none",
                });
                this.btnLoading = false;
              }
            } else {
            }
          })
          .catch(() => {
            // 处理验证错误
          });
      }
    },
    handleUnbinding(params) {
      console.log("params", params);
      this.unBindData = params;
      console.log("unBindData", this.unBindData);
      // this.siteUnbinding.name = params.siteName;
      this.isShowModal = true;
    },
    addSite() {
      this.isShowPoup = true;
      console.log(1, this.isShowPoup);
    },
    close() {
      this.isShowPoup = false;
    },
    async onSelectBinDing(e) {
      this.bindingType = e.type;
      if (this.bindingType == 2) {
        this.isShowPoup = false;
        uni.navigateTo({
          url: "/pages/dashboard/bindTheSite",
        });
      } else if (this.bindingType == 1) {
        permision.checkScanCodePermissions("camera").then((res) => {
          if (res) {
            uni.scanCode({
              hideAlbum: true,
              onlyFromCamera: true,
              success: (result) => {
                let params = {
                  emsCode: result.result,
                };
                apis.addSearchSite(params).then((res) => {
                  if (res.code == 200) {
                    uni.navigateTo({
                      url: `/pages/dashboard/scanBingDing?data=${JSON.stringify(
                        res.data
                      )}`,
                    });
                  }
                });
              },
              fail: (err) => {
                uni.showToast({
                  title: this.$t("common.scanErr"),
                  icon: "none",
                });
              },
            });
          } else {
            uni.showModal({
              title: this.$t("common.permissionPrompts"),
              content: `${this.$t("common.pleaseGrant")}${this.$t(
                "common.camera"
              )}${this.$t("common.permissionToUseTheFeature")}`,
              confirmText: this.$t("common.goToSettings"),
              cancelText: this.$t("common.cancel"),
              success: (res) => {
                if (res.confirm) {
                  uni.openAppAuthorizeSetting();
                }
              },
            });
          }
        });
      }
    },
    // 上拉加载处理方法
    async fetchData(callback) {
      if (this.pageNum == 1) {
        this.dataList = [];
      }
      let params = {
        siteType: cookie.get("siteType"),
        current: this.pageNum,
        limit: 10,
        keywords: this.searchVal,
      };
      apis.getSiteList(params).then((res) => {
        let data = res.data.records;
        this.dataList = this.dataList.concat(data);
        if (data.length < 10) {
          this.loadMoreStatus = "nomore";
        } else {
          this.loadMoreStatus = "loading";
        }
      });

      if (callback) {
        callback();
      }
    },
  },

  onPullDownRefresh() {
    this.pageNum = 1; // 重置页码
    this.loadMoreStatus = "more"; // 重置加载状态
    // 下拉刷新时重新获取数据
    this.fetchData(() => {
      // 数据获取完成后停止下拉刷新动画
      uni.stopPullDownRefresh();
    });
  },
  onReachBottom() {
    if (this.loadMoreStatus == "nomore") return; // 如果没有更多数据，直接返回
    this.loadMoreStatus = "loading";
    this.pageNum++;
    this.fetchData();
  },
  onHide() {
    this.isShow = false;
  },
};
</script>

<style lang="scss" scoped>
:deep(.u-loadmore) {
  margin-top: 0 !important;
  margin-bottom: 40rpx !important;
}

.popup {
  width: 100%;
  max-height: 50vh;
  overflow-y: scroll;
  padding: 100rpx 0;
  box-sizing: border-box;

  .header {
    width: 100%;
    position: relative;
    text-align: center;
    padding: 30rpx 56rpx;
    box-sizing: border-box;

    .title {
      font-family: Alibaba PuHuiTi 3;
      font-size: 34rpx;
      font-weight: 500;
      font-variation-settings: "opsz" auto;
      /* 白 */
      color: #ffffff;
    }

    .selected {
      position: absolute;
      top: 30rpx;
      right: 56rpx;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      image {
        width: 32rpx;
        height: 32rpx;
        margin-right: 10rpx;
      }

      text {
        font-family: Alibaba PuHuiTi 3;
        font-size: 28rpx;
        font-weight: 500;
        font-variation-settings: "opsz" auto;
        font-feature-settings: "kern" on;
        /* 白 */
        color: #ffffff;
      }
    }
  }

  .locale-list {
    width: 520rpx;
    margin: 0 auto;

    .locale-item {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      background-color: #132034;
      font-size: 32rpx;
      font-weight: 500;
      text-align: center;
      color: #ffffff;
      border: 1rpx solid #1f3651;
      border-radius: 50rpx;
      margin-bottom: 30rpx;
    }

    .locale-item-active {
      background-color: $locale-background-color;
    }
  }
}

.search {
  width: 100%;
  border-top: 1rpx solid #0b1523;
  padding: 23rpx 32rpx;
  box-sizing: border-box;
  background-color: #132034;
  position: fixed;
  z-index: 999999999;
}

:deep(.u-search__content__input) {
  background-color: #222d49 !important;
}

:deep(.u-search__content) {
  background-color: #222d49 !important;
}

:deep(.u-search__action) {
  color: #64b7f6;
}

.modal-content {
  max-width: 84vw !important;
  max-height: 70vh;
  overflow-y: scroll;
  padding: 48rpx 0 0;
  box-sizing: border-box;

  .title {
    width: 100%;
    text-align: center;
    margin-bottom: 42rpx;

    font-family: Alibaba PuHuiTi 3;
    font-size: 36rpx;
    font-weight: 500;
    font-variation-settings: "opsz" auto;
    color: #dddddd;
  }

  .header {
    font-family: Alibaba PuHuiTi 3;
    font-size: 32rpx;
    font-weight: normal;
    font-variation-settings: "opsz" auto;
    color: #aeaeae;
    margin-bottom: 33rpx;
    padding: 0 48rpx;
    box-sizing: border-box;
  }

  .modal-content-input {
    width: 100%;
    padding: 0 48rpx;
    box-sizing: border-box;

    .siteUnbinding-input {
      width: 100%;
      height: 88upx;
      background-color: #222d49;
      border-radius: 150upx;
      z-index: 1;
      padding: 0 36upx !important;
      box-sizing: border-box;
    }
  }

  :deep(.u-form-item__body__right__message) {
    margin-left: 0 !important;
  }

  .footer {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1rpx solid #08121e;
    margin-top: 45rpx;

    .btn {
      background-color: transparent;
      border-color: transparent;
      padding: 50rpx 0;
      box-sizing: border-box;
      font-family: PingFang SC Regular;
      font-size: 34rpx;
      line-height: 34px;
      text-align: center;
      color: #64b7f6;
    }

    .addborder {
      border-right: 1rpx solid #08121e;
      color: #aeaeae;
    }
  }
}

button::after {
  display: none;
}

button::before {
  display: none;
}

.ops-add {
  width: 36rpx;
  height: 36rpx;
}

:deep(.u-modal__button-group__wrapper--cancel) {
  border-right: 1rpx solid #08121e !important;
}
</style>
